package com.hangyutech.strelitzia.interceptor;

import com.hangyutech.strelitzia.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 557 做登陆拦截.
 *
 * @author WiconWang <WiconWang@gmail.com>
 * @copyright 2020/12/4 3:55 PM
 */


public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            response.getWriter().print("用户未登录，请登录后操作！");
            return false;

//            return HttpResult.error().message("用户未登录，请登录后操作！");
        }
        Object loginStatus = redisService.get(token);
        if (Objects.isNull(loginStatus)) {
            response.getWriter().print("身份验证失败，请重新登陆，请查看！");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}